package com.kingbook.services;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.kingbook.common.cache.JedisUtils;
import com.kingbook.common.thread.Threads;
import com.kingbook.core.base.SupportService;
import com.kingbook.entity.SmsTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Bucky
 * @Date 2020-04-26 11:10:45
 * @Version 1.0
 */
@Slf4j
@Service
public class SmsService extends SupportService {

    @Autowired
    ConfigService configService;

    private final static String VERSION = "2017-05-25"; //该API的版本号，格式为YYYY-MM-DD,不能改

    private final static String ACTION = "SendSms";

    private final static String TEMPLATE_CODE = "SMS_189521545";

    private final static String SIGN_NAME = "金山账本";


    @PostConstruct
    private void init() {
        setNamespace("Sms");
    }

    /**
     * {
     * "Message": "OK",
     * "RequestId": "873043ac-bcda-44db-9052-2e204c6ed20f",
     * "BizId": "607300000000000000^0",
     * "Code": "OK"
     * }
     */
    boolean sendSmsAndCache(String phoneNo, String vCode) {
        String resCode = "OK", resMessage = "Mock";
        SmsTemplate template = configService.querySmsTemplate();
        if (JedisUtils.set("VCode:" + phoneNo, vCode, template.getTimeout())) {
            if (template.isRealSend()) {
                try {
                    template.checkEmpty();
                    DefaultProfile profile = DefaultProfile.getProfile(template.getRegionId(), template.getAccessKeyId(), template.getAccessKeySecret());
                    IAcsClient client = new DefaultAcsClient(profile);
                    CommonRequest request = new CommonRequest();
                    request.setSysMethod(MethodType.POST);
                    request.setSysDomain(template.getDomainUrl());
                    request.setSysVersion(VERSION);
                    request.setSysAction(ACTION);
                    request.putQueryParameter("RegionId", template.getRegionId());
                    request.putQueryParameter("PhoneNumbers", phoneNo);
                    request.putQueryParameter("SignName", SIGN_NAME);
                    request.putQueryParameter("TemplateCode", TEMPLATE_CODE);
                    request.putQueryParameter("TemplateParam", "{\"code\":\"" + vCode + "\"}");
                    CommonResponse response = client.getCommonResponse(request);
                    JSONObject json = JSONObject.parseObject(response.getData());
                    resCode = json.getString("Code");
                    resMessage = json.getString("Message");
                } catch (Exception e) {
                    resCode = e.getClass().getSimpleName();
                    resMessage = e.getLocalizedMessage();
                    log.error("---->发送短信异常 resCode:{} resMessage:{}", resCode, resMessage);
                    if (resMessage.length() > 100) {
                        resMessage = resMessage.substring(0, 99);
                    }
                }
            }
        } else {
            resCode = "CACHE_FAIL";
            resMessage = "Redis Cache Error";
        }
        saveSms(phoneNo, vCode, resCode, resMessage);
        return "OK".equalsIgnoreCase(resCode);
    }

    private void saveSms(String phone, String vCode, String resCode, String resMessage) {
        Threads.asyncExecute(() -> {
            log.info("---->发送短信: {} -> {} resMessage:{}", phone, vCode, resMessage);
            Map<String, Object> param = new HashMap<>(6);
            param.put("phone", phone);
            param.put("vCode", vCode);
            param.put("templateCode", TEMPLATE_CODE);
            param.put("resCode", resCode);
            param.put("resMessage", resMessage);
            insert("saveSms", param);
        });
    }

}
